/*!
  @file transporter_client.cpp
  @brief Brief description
  @author Kyohei Otsu <kyohei@kth.se>
  @date 2013
*/

#include <arpa/inet.h>
#include "net/io.h"
#include "net/text_handler.h"
#include "net/transporter.h"
#include "core/core.h"

namespace net
{

void Transporter::connectToServer()
{
  //! set ip address
  memset(&addr_, 0, sizeof(addr_));
  addr_.sin_family = AF_INET;
  addr_.sin_port = htons(port_);
  //addr_.sin_addr.s_addr = inet_addr(ipaddr.c_str());
  
  //-- socket open
  sock_ = socket(AF_INET, SOCK_STREAM, 0);
  if (sock_ < 0) {
    ERROR("Socket open failed");
    return;
  }

  //-- connect
  int rc = connect(sock_, (struct sockaddr *)&addr_, sizeof(addr_));
  if (rc != 0) {
    ERROR("Socket connect failed");
    return;
  }

  NETINFO(addr_, "connection established");

  //-- create data handler
  TextHandler::Ptr handler(new TextHandler(sock_, "r+b"));
  handler->startThreads();
  data_handlers_.push_back(handler);
}

} // end of namespace
